<template>
    <div class="home_div">
        <!-- <div class="map-title">
            <h3>JSAPI Vue3地图组件示例</h3>
            <div v-if="back" id="back" @click="showAllMap" style="cursor: pointer;">返回</div>
        </div> -->
        <div id="container"></div>
        <div class="floating-panel">
            <div v-for="(item, index) in floatingItems" :key="index" class="floating-item">
                <img :src="item.icon" :alt="item.name" class="item-icon" />
                <span class="item-name">{{ item.name }}</span>
            </div>
        </div>
    </div>
</template>
<script setup lang="ts">
import AMapLoader from "@amap/amap-jsapi-loader";
import { shallowRef, ref, onMounted, toRaw } from "vue";
import { qingyunMapData } from "@/utils/qingyun";
const floatingItems = ref([
    {
        icon: 'https://image.shengxuankj.com/daping/red.png',
        name: '无人驾驶物流车'
    }
]);
// 类型定义
interface MarkerDataTs {
    longitude: number;
    latitude: number;
    name: string;
    icon: string;
    type: number;
}

interface ColorMap {
    [key: string]: string;
}

// 响应式数据
const map = shallowRef<any>(null);
const AMap = shallowRef<any>(null) as any;
const back = ref<boolean>(false);
const polygons = shallowRef<any[]>([]);
const district = shallowRef<any>(null);
const polygon = shallowRef<any>(null);
const markers = shallowRef<any[]>([]);

// 方法定义
const markerData = ref<MarkerDataTs[]>([])

/*  
返回区域对应颜色
adcode:厦门市	        350200
        厦门市市辖区	350201
        思明区	        350203
        海沧区	        350205
        湖里区	        350206
        集美区	        350211
        同安区	        350212
        翔安区	        350213
        */
// const getColorByAdcode = (adcode: string): string => {
//     const colors: ColorMap = {
//         "350200": "#111111",
//         "350201": "#456aed",
//         "350203": "428cced",
//         "350205": "#a456e1",
//         "350206": "#123fee",
//         "350211": "#666eee",
//         "350212": "#963qde",
//         "350213": "#784eda",
//     };
//     return colors[adcode];
// };
// 初始化遮罩
const initArea = (city: string, isChildDraw: boolean = false): void => {
    district.value.search(city, function (status: string, result: any) {
        // 外多边形坐标数组和内多边形坐标数组
        const outer = [
            new AMap.value.LngLat(-360, 90, true),
            new AMap.value.LngLat(-360, -90, true),
            new AMap.value.LngLat(360, -90, true),
            new AMap.value.LngLat(360, 90, true),
        ];
        // console.log(result);

        // 绘制遮罩
        const holes = result.districtList[0].boundaries;
        const pathArray = [outer];
        pathArray.push.apply(pathArray, holes);
        polygon.value = new AMap.value.Polygon({
            pathL: holes,
            strokeColor: "#253042",
            strokeWeight: 1,
            fillColor: "#071023",
            fillOpacity: 1,
        });
        polygon.value.setPath(pathArray);
        map.value.add(polygon.value);
        areaPolyline(result.districtList[0].districtList[0].adcode);
    });
};
// 添加自定义标记点
const addCustomMarkers = (): void => {
    // 清除已有标记点
    if (markers.value.length) {
        map.value.remove(markers.value);
        markers.value = [];
    }
    
    // 定义四个点位的坐标和信息
    // const markerData: MarkerData[] = [
    //     {
    //         position: [117.3856, 37.8452], // 点位1坐标
    //         title: '绿电供应',
    //         content: '这是一个绿电供应标点',
    //         icon: `https://image.shengxuankj.com/daping/green-power.svg`
    //     },
    //     {
    //         position: [117.4412, 37.7658], // 点位2坐标
    //         title: '共享换电',
    //         content: '这是一个共享换电标点',
    //         icon: 'https://image.shengxuankj.com/daping/shared-battery.svg'
    //     },
    //     {
    //         position: [117.3698, 37.7825], // 点位3坐标
    //         title: '共享出行',
    //         content: '这是一个共享出行标点',
    //         icon: 'https://image.shengxuankj.com/daping/shared-travel.svg'
    //     },
    //     {
    //         position: [117.3945, 37.7589], // 点位4坐标
    //         title: '共享运力',
    //         content: '这是一个共享运力标点',
    //         icon: 'https://image.shengxuankj.com/daping/red.png'
    //     }
    // ];
    
    // 创建标记点
    console.log('标点啦~~~~',markerData.value)
    markerData.value.forEach((data, index) => {
        // 创建自定义图标
        const customIcon = new AMap.value.Icon({
            size: new AMap.value.Size(20, 20), // 图标大小
            image: data.icon, // 引用服务器SVG图标
            imageSize: new AMap.value.Size(20, 20)
        });
        const marker = new AMap.value.Marker({
            position: [data.longitude, data.latitude],
            icon: customIcon,
            title: data.name,
            offset: new AMap.value.Pixel(-16, -16), // 图标偏移量
        });
        
        // 添加点击事件
        marker.on('click', () => {
            const infoWindow = new AMap.value.InfoWindow({
                content: `<div style="padding: 10px;"><h4>${data.name}</h4></div>`,
                offset: new AMap.value.Pixel(0, -30)
            });
            infoWindow.open(map.value, [data.longitude, data.latitude]);
        });
        
        markers.value.push(marker);
    });
    
    // 添加到地图
    map.value.add(markers.value);
};
// 显示总览
const showAllMap = (): void => {
    back.value = false;
    if (polygon.value) {
        // 清除遮罩
        map.value.remove(polygon.value);
    }
    initArea("庆云县", true);
    // map.value.setCenter([118.113994, 24.614998]);
    map.value.setCenter([117.420507, 37.827724]);

    map.value.setZoom(11);
    // 重新添加标记点
    addCustomMarkers();
};
// 绘制区域描边
const areaPolyline = (adcode: string): void => {
    if (polygons.value.length) {
        map.value.remove(polygons.value);
        polygons.value = [];
    }
    district.value.search(adcode, function (status: string, result: any) {
        //   绘制区域描边
        const bounds = result.districtList[0].boundaries;
        for (let i = 0; i < bounds.length; i++) {
            // const color = getColorByAdcode(result.districtList[0].adcode);
            const polygonItem = new AMap.value.Polygon({
                path: bounds[i],
                strokeColor: "#253042",
                strokeWeight: 2,
                fillColor: "#784eda",
                fillOpacity: 0,
            });
            // 添加监听事件
            // polygonItem.on("mouseover", () => {
            //     if (!back.value) {
            //         polygonItem.setOptions({
            //             fillOpacity: 0.7,
            //         });
            //     }
            // });
            // 添加点击事件
            polygonItem.on("click", () => {
                // 判断是否为市级
                if (!back.value) {
                    // 显示返回按钮
                    back.value = true;
                    map.value.setZoom(12);
                    // 修改中心位置为区级中心
                    map.value.setCenter([
                        result.districtList[0].center.lng,
                        result.districtList[0].center.lat,
                    ]);
                    //   绘画
                    initArea(result.districtList[0].adcode, false);
                }
            });
            polygonItem.on("mouseout", () => {
                polygonItem.setOptions({
                    fillOpacity: 0,
                });
            });
            polygons.value.push(polygonItem);
        }
        map.value.add(polygons.value);
    });
};
const getMaskJson = (): any => {
    const list = qingyunMapData.features[0].geometry.coordinates[0];
    return list;
};

const ininMap = (): void => {
    // 这个配置很重要，必须设置，否则你的 行政服务搜索api无法使用生成回调
    (window as any)._AMapSecurityConfig = {
        securityJsCode: "587b22815e6cc6b14effaa607c627fb7",
    };
    AMapLoader.load({
        key: "e6072f86d2d66d78671eaa4542006354", //设置您的key
        version: "2.0",
        plugins: [
            "AMap.ToolBar",
            "AMap.Driving",
            "AMap.Polygon",
            "AMap.DistrictSearch",
            "AMap.Object3DLayer",
            "AMap.Object3D",
            "AMap.Polyline",
            "AMap.Marker",
            "AMap.InfoWindow",
            "AMap.Icon",
            "AMap.Weather",
            "AMap.RoadInfoSearch"
        ],
        AMapUI: {
            version: "1.1",
            plugins: [],
        },
        Loca: {
            version: "2.0.0",
        },
    })
        .then((AMapInstance) => {
            AMap.value = AMapInstance;
            map.value = new AMapInstance.Map("container", {
                viewMode: "3D",
                zoom: 10.5,
                zooms: [10, 20],
                center: [117.420507, 37.827724],
                mapStyle: 'amap://styles/dark',
                features: ["bg", "road"],
                mask: getMaskJson()
            });
            district.value = new AMapInstance.DistrictSearch({
                subdistrict: 3, //获取边界返回下级行政区
                extensions: "all", //返回行政区边界坐标组等具体信息
                // level: "city", //查询行政级别为 市
                level: "district", //查询行政级别为 市

            });

            // let obj = new AMapInstance.RoadInfoSearch

            initArea("庆云县", true);
            // 添加自定义标记点
            addCustomMarkers();
        })
        .catch((e) => {
            console.log(e);
        });
};
// 生命周期钩子
onMounted(() => {
    //DOM初始化完成进行地图初始化
    let timer = setTimeout(() => {
        ininMap();
        clearTimeout(timer);
    }, 500);
});

const getPointData = (pointList: any) => {
    console.log('获取点位啦~~~~',pointList)

    markerData.value = JSON.parse(pointList).mapPoints
}


defineExpose({
    getPointData
})



</script>
<style scope>
.home_div {
    height: 100%;
    width: 100%;
    padding: 0px;
    margin: 0px;
    position: relative;
}

#container {
    height: 100%;
    width: 100%;
    padding: 0px;
    margin: 0px;
    background-color: transparent !important;
}

.map-title {
    position: absolute;
    z-index: 1;
    width: 100%;
    height: 50px;
    background-color: rgba(27, 25, 27, 0.884);
    display: flex;
    justify-content: space-around;
    align-items: center;
}

h3 {
    z-index: 2;
    color: white;
}
.amap-container {
    background-image: none !important;
}

/* 悬浮框样式 */
.floating-panel {
    position: absolute;
    top: 20px;
    left: 20px;
    z-index: 1000;
    background: rgba(0, 0, 0, 0.8);
    border-radius: 8px;
    padding: 15px 20px;
    /* min-width: 200px; */
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.1);
}

.floating-item {
    display: flex;
    align-items: center;
    /* margin-bottom: 12px; */
    padding: 8px;
    border-radius: 6px;
    transition: background-color 0.3s ease;
}

.floating-item:last-child {
    margin-bottom: 0;
}

/* .floating-item:hover {
    background-color: rgba(255, 255, 255, 0.1);
    cursor: pointer;
} */

.item-icon {
    width: 24px;
    height: 24px;
    margin-right: 12px;
    border-radius: 4px;
    object-fit: cover;
}

.item-name {
    color: #ffffff;
    font-size: 14px;
    font-weight: 500;
    white-space: nowrap;
}
</style>